from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info import constants, db
from info.models import User, News, Category, Comment, CommentLike
from info.utilities.response_code import RET
from . import newsdetail_bp
from flask import render_template
from info.utilities.common import user_login_data


# 127.0.0.1:5000/news/comment_like
@newsdetail_bp.route('/comment_like', methods=["POST"])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        current_app.logger.error("用户未登录")
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    param_dict = request.json
    comment_id = param_dict.get("comment_id")
    action = param_dict.get("action")

    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if action not in["add", "remove"]:
        current_app.logger.error("参数错误")
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询评论对象异常")

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论不存在，不能点赞")

    if action == "add":
        comment_like = None
        try:
            comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                    CommentLike.user_id == user.id
                                                    ).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询评论点赞中间表对象异常")

        if not comment_like:
            comment_like_obj = CommentLike()
            comment_like_obj.user_id = user.id
            comment.like_count += 1
            comment_like_obj.comment_id = comment_id

            db.session.add(comment_like_obj)
    else:
        try:
            comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                    CommentLike.user_id == user.id
                                                    ).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询评论点赞中间表对象异常")

        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")

    return jsonify(errno=RET.OK, errmsg="OK")


@newsdetail_bp.route('/news_comment', methods=["POST"])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        current_app.logger.error("用户未登录")
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    param_dict = request.json
    news_id = param_dict.get("news_id")
    comment_str = param_dict.get("comment")
    # 如果有值，表示这是一条子评论
    parent_id = param_dict.get("parent_id")

    if not all([news_id, comment_str]):
        current_app.logger.error("参数不足")
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻异常")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在，不能发表评论")

    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news.id
    comment.content = comment_str

    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存评论对象异常")

    # 评论需要返回数据给前端显示
    return jsonify(errno=RET.OK, errmsg="OK", data=comment.to_dict())


# 127.0.0.1:5000/news/news_collect
@newsdetail_bp.route('/news_collect', methods=["POST"])
@user_login_data
def news_collect():
    """收藏，取消收藏的后端接口"""
    user = g.user
    if not user:
        current_app.logger.error("用户未登陆")
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
    params_dict = request.json
    news_id = params_dict.get("news_id")
    action = params_dict.get("action")

    if not all([news_id, action]):
        current_app.logger.error("参数不足")
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if action not in ["collect", "cancel_collect"]:
        current_app.logger.error("参数错误")
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象异常")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    if action == "collect":
        user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象异常")

    return jsonify(errno=RET.OK, errmsg="OK")


# 127.0.0.1:5000/news/新闻id
# 展示新闻详情页面
@newsdetail_bp.route('/<int:news_id>')
@user_login_data
def newsdetail(news_id):

    # user_id = session.get("user_id")
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")

    user = g.user

    # ****************查询新闻点击排行***********************
    try:
        news_rank_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻数据异常")

    news_dict_list = []
    # if news_rank_list:
    #     for news_obj in news_rank_list:
    #         news_dict = news_obj.to_dict()
    #         news_dict_list = news_dict_list.append(news_dict)
    for news_obj in news_rank_list if news_rank_list else []:
        news_dict = news_obj.to_dict()
        news_dict_list.append(news_dict)

    # ****************根据新闻id查询新闻数据***********************
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象异常")

    if news:
        news_dict = news.to_dict()

    # ****************查询当前用户是否收藏该新闻***********************

    is_collected = False

    # 当用户处于登陆状态时，才查询是否收藏
    if user:
        if news in user.collection_news:
            is_collected = True

    # ****************5. 获取新闻评论列表数据***********************
    try:
        news_comment_list = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")

    commentlike_id_list = []
    if user:
        # ****************6. 查询当前用户具体对那几条评论点过赞 ***********************
        comment_id_list = [comment.id for comment in news_comment_list]

        try:
            commentlike_obj_list = CommentLike.query.filter(CommentLike.comment_id.in_(comment_id_list),
                                                            CommentLike.user_id == user.id
                                                            ).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")

        commentlike_id_list = [commentlike_obj.comment_id for commentlike_obj in commentlike_obj_list]

    comment_dict_list = []
    for comment_obj in news_comment_list if news_comment_list else []:
        comment_dict = comment_obj.to_dict()
        comment_dict["is_like"] = False
        if comment_obj.id in commentlike_id_list:
            comment_dict["is_like"] = True
        comment_dict_list.append(comment_dict)






    # if user:
    #     user_dict = user.to_dict()
    data = {
        "user_info": user.to_dict() if user else None,
        "news_rank_list": news_dict_list,
        "news": news_dict,
        "is_collected": is_collected,
        "comments": comment_dict_list
    }

    return render_template("news/detail.html", data=data)
